package com.xsoft.common.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * created by zhangkai on 2020/6/3
 * email: 405547628@qq.com
 * desc:
 */
public class ApplicationUtils {
    private static WeakReference<Activity> activityWeakReference;
    private static boolean isListening;//是否正在监听activityLifecycle,避免重复监听

    /**
     * 获取application
     *
     * @return
     */
    public static Application getApplication(Context context) {
        Context application = context.getApplicationContext();
        if (application == null) {
            application = getApplicationByReflect();
        }
        return (Application) application;
    }

    /**
     * 监听activity生命周期，以获取当前activity
     *
     * @param context
     */
    public static void registerActivityLifecycleCallbacks(Context context) {
        if (isListening) {
            return;
        }
        getApplication(context).registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                if (activityWeakReference != null) {
                    activityWeakReference.clear();
                }
                activityWeakReference = new WeakReference<>(activity);
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {

            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {

            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                if (activityWeakReference != null) {
                    activityWeakReference.clear();
                }
            }
        });
        isListening = true;
    }

    /**
     * 通过反射获取application实例
     *
     * @return
     */
    public static Application getApplicationByReflect() {
        try {
            @SuppressLint("PrivateApi")
            Class<?> activityThread = Class.forName("android.app.ActivityThread");
            Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
            Object app = activityThread.getMethod("getApplication").invoke(thread);
            if (app == null) {
                throw new NullPointerException("you should init first");
            }
            return (Application) app;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        throw new NullPointerException("you should init first");
    }

    public static Activity getTopActivity() {
        if (activityWeakReference == null || activityWeakReference.get() == null) {
            throw new NullPointerException("当前top activity为空，请检查是否监听activity生命周期");
        }
        return activityWeakReference.get();
    }
}
